package com.zhht.checkcop.util;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.zhht.checkcop.db.MysqlDb;

/**
 * HttpClient工具类
 */
public class HttpClientUtil {

    /**请求编码*/
    private static final String DEFAULT_CHARSET = "UTF-8";

    /**
     * 执行HTTP POST请求
     * @param url url
     * @param param 参数
     * @return
     */
    public static String httpPostWithJSON(String url, Map<String, ?> param) {
        CloseableHttpClient client = null;
        try {
            if(url == null || url.trim().length() == 0){
                throw new Exception("URL is null");
            }
            HttpPost httpPost = new HttpPost(url);
            client = HttpClients.createDefault();
            if(param != null){
                StringEntity entity = new StringEntity(JSON.toJSONString(param), DEFAULT_CHARSET);//解决中文乱码问题
                entity.setContentEncoding(DEFAULT_CHARSET);
                entity.setContentType("application/json");
                httpPost.setEntity(entity);
            }
            HttpResponse resp = client.execute(httpPost);
            if(resp.getStatusLine().getStatusCode() == 200) {
                return EntityUtils.toString(resp.getEntity(), DEFAULT_CHARSET);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(client);
        }
        return null;
    }

    /**
     * 执行HTTP GET请求
     * @param url url
     * @param param 参数
     * @return
     */
    public static String httpGetWithJSON(String url, Map<String, ?> param) {
        CloseableHttpClient client = null;
        try {
            if(url == null || url.trim().length() == 0){
                throw new Exception("URL is null");
            }
            client = HttpClients.createDefault();
            if(param != null){
                StringBuffer sb = new StringBuffer("?");
                for (String key : param.keySet()){
                    sb.append(key).append("=").append(param.get(key)).append("&");
                }
                url = url.concat(sb.toString());
                url = url.substring(0, url.length()-1);
            }
            HttpGet httpGet = new HttpGet(url);
            HttpResponse resp = client.execute(httpGet);
            if(resp.getStatusLine().getStatusCode() == 200) {
                return EntityUtils.toString(resp.getEntity(), DEFAULT_CHARSET);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(client);
        }
        return null;
    }

    /**
     * 关闭HTTP请求
     * @param client
     */
    private static void close(CloseableHttpClient client){
        if(client == null){
            return;
        }
        try {
            client.close();
        } catch (Exception e) {
        }
    }

    public static void main(String[] args) throws Exception {
    	MysqlDb mysqldb = new MysqlDb();
    	mysqldb.connect();
    	
    	List<Map<String, Object>> query = mysqldb.query("select gsw.* from t_gsw_gj gsw LEFT JOIN t_gf_book tgb on tgb.`name` = gsw.nameStr where tgb.id is null");
    	for(Map<String, Object> mm:query){
    		
    	}
    	
	}
    
//    /**
//     * 古诗文网  扒书籍
//     * @param url
//     * @return
//     */
//    public static void main(String[] args) throws Exception {
////        Map param = new HashMap();
////        param.put("page", "7");
////        param.put("token", "gswapi");
////        String result = httpPostWithJSON("https://app.gushiwen.cn/api/Default.aspx", param);
////        System.out.println("result:"+result);
//    	MysqlDb mysqldb = new MysqlDb();
//    	mysqldb.connect();
////    	mysqldb.execDB("update t_gsw_chapter set cont = '𩳁' where id = 8933");
//    	List<Map<String, Object>> query = mysqldb.query("select * from t_gsw_chapter where id = 8933");
//    	
//    	String ssss  =  new String((query.get(0).get("cont")+"").getBytes("ISO-8859-1"),"utf8");
//    	System.out.println(ssss);
//    	
////    	 String result = post("https://app.gushiwen.cn/api/guwen/Default.aspx?page=2&type=%E7%BB%8F%E9%83%A8&token=gswapi");  
////    	 String result = post("https://app.gushiwen.cn/api/guwen/Default.aspx?page=7&type=%e5%8f%b2%e9%83%a8&token=gswapi");  
////    	 String result = post("https://app.gushiwen.cn/api/guwen/Default.aspx?page=7&type=%e5%ad%90%e9%83%a8&token=gswapi");  
//    	 String result = post("https://app.gushiwen.cn/api/guwen/Default.aspx?page=1&type=%e5%ad%90%e9%83%a8&token=gswapi");  
//         
//         System.out.println(result);
//         if(result != null){
//        	 Map maps = (Map)JSON.parse(result.replace("􏷣", ""));  
//        	 JSONArray json = (JSONArray) maps.get("books");
//        	 System.out.println("books   总数："+json.size());
//        	 for(int i=2;i<json.size();i++) {
//        		 String id = json.getJSONObject(i).get("id") +"";
//        		 System.out.println(id);
//        		 //保存book
//        		 Map bookMap = json.getJSONObject(i);
//        		 bookMap.remove("creTime");
//        		 bookMap.remove("id");
//        		 String bookId = "";
//        		 try{
//        			 bookId = mysqldb.executeInsertById("t_gsw_gj",bookMap);
//	        	 }catch(Exception e){
//	        		 e.printStackTrace();
//	        	 }
//                 String result2 = post("https://app.gushiwen.cn/api/guwen/book.aspx?id="+id+"&token=gswapi");
//                 System.out.println(result2);
//                 Map result2Map = (Map)JSON.parse(result2);
//                 if(result2Map.get("tb_bookviews")!=null){
//                	 Map result3Map = (Map)JSON.parse(result2Map.get("tb_bookviews").toString());
//                	 JSONArray json2 = (JSONArray) result3Map.get("bookviews");
//                	 for(int j=0;j<json2.size();j++) {
//                		 String id2 = json2.getJSONObject(j).get("id") +"";
//                         System.out.println(id2);
//                         String result3 = post("https://app.gushiwen.cn/api/guwen/bookv.aspx?id="+id2+"&token=gswapi");
//                         System.out.println(result3);
//                         Map result4Map = (Map)JSON.parse(result3.replace("􏷣", "").replace("􊶼", "").replace("��", "").replace("���", "").replace("��", "").replace("���", "").replace("��", ""));
//                         if(result4Map.get("tb_bookview")!=null){
//                        	 Map chapterMap = new HashMap();
//                        	 Map result5Map = (Map)JSON.parse(result4Map.get("tb_bookview").toString());
//                        	 String chapterCont = result5Map.get("cont")+"";
//                        	 String num = result5Map.get("num")+"";
//                        	 String nameStr = result5Map.get("nameStr")+"";
//                        	 String author = result5Map.get("author")+"";
//                        	 String fenlei = result5Map.get("fenlei")+"";
//                        	 String yiyi = result5Map.get("yiyi")+"";
//                        	 Map result6Map = (Map)JSON.parse(result4Map.get("tb_fanyis").toString());
//                        	 JSONArray bvfanyis = (JSONArray) result6Map.get("bvfanyis");
//                        	 if(bvfanyis.size()>0){
//                        		 String cankao = bvfanyis.getJSONObject(0).get("cankao")+"";
//                        		 String cont = bvfanyis.getJSONObject(0).get("cont")+"";
//                        		 String fyauthor = bvfanyis.getJSONObject(0).get("author")+"";
//                        		 chapterMap.put("fycont", cont);
//                        		 chapterMap.put("fyauthor", fyauthor);
//                        		 chapterMap.put("cankao", cankao);
//                        	 }
//                        	 Map result7Map = (Map)JSON.parse(result4Map.get("tb_shangxis").toString());
//                        	 String bvshangxis = result7Map.get("bvshangxis")+"";
//                        	 chapterMap.put("sxcont", bvshangxis);
//                        	 Map result8Map = (Map)JSON.parse(result4Map.get("tb_author").toString());
//                        	 String authorCont = result8Map.get("cont")+"";
//                        	 chapterMap.put("zzcont", authorCont);
//                        	 
//                        	 
//                        	 chapterMap.put("bookID", bookId);
//                        	 chapterMap.put("num", num);
//                        	 chapterMap.put("nameStr", nameStr);
//                        	 chapterMap.put("author", author);
//                        	 chapterMap.put("cont", chapterCont);
//                        	 chapterMap.put("bookName", bookMap.get("nameStr"));
//                        	 chapterMap.put("fenlei", fenlei);
//                        	 chapterMap.put("yiyi", yiyi);
//                        	 try{
//                        	 //保存章节
//                        		 mysqldb.insert("t_gsw_chapter",chapterMap);
//                        	 }catch(Exception e){
//                        		 System.out.println(chapterMap.remove("fycont"));
//                        		 System.out.println(chapterMap.remove("cont"));
//                        		 mysqldb.insert("t_gsw_chapter",chapterMap);
//                        		 e.printStackTrace();
//                        	 }
//                        	 
//                         }
//                	 }
//                 }
//                 
//                 
//             }
//         }
//    }

	private static String post(String url) {
		HttpClient httpClient = null;  
         HttpPost httpPost = null;  
         String result = null;  
         try{  
             httpClient = new SSLClient();  
             httpPost = new HttpPost(url);  
             httpPost.addHeader("Content-Type", "application/json");  
//             StringEntity se = new StringEntity(JSON.toJSONString(param));  
//             se.setContentType("text/json");  
//             se.setContentEncoding(new BasicHeader("Content-Type", "application/json"));  
//             httpPost.setEntity(se);  
             HttpResponse response = httpClient.execute(httpPost);  
             if(response != null){  
                 HttpEntity resEntity = response.getEntity();  
                 if(resEntity != null){  
                     result = EntityUtils.toString(resEntity,"utf-8");  
                 }  
             }  
         }catch(Exception ex){  
             ex.printStackTrace();  
         }
		return result;
	}
	private static String get(String url) {
		HttpClient httpClient = null;  
		HttpGet httpget = null;  
		String result = null;  
		try{  
			httpClient = new SSLClient();  
			httpget = new HttpGet(url);  
			httpget.addHeader("Content-Type", "application/json");  
//             StringEntity se = new StringEntity(JSON.toJSONString(param));  
//             se.setContentType("text/json");  
//             se.setContentEncoding(new BasicHeader("Content-Type", "application/json"));  
//             httpPost.setEntity(se);  
			HttpResponse response = httpClient.execute(httpget);  
			if(response != null){  
				HttpEntity resEntity = response.getEntity();  
				if(resEntity != null){  
					result = EntityUtils.toString(resEntity,"utf-8");  
				}  
			}  
		}catch(Exception ex){  
			ex.printStackTrace();  
		}
		return result;
	}


}